import { createSlice, PayloadAction,createAsyncThunk } from '@reduxjs/toolkit'
import type { RootState } from './store'
import { Comment } from '@react-vant/icons';

interface Comment {
    id: number;
    content: string;
    author: string;
    timestamp: string;
}

interface CommentsState {
    comments: Comment[]
}
const initialState: CommentsState = {
    comments: JSON.parse(localStorage.getItem('follow') || '[]') as any
}
export const commentsSlice= createSlice({
    name: 'comments',
    initialState,
    reducers: {
        addComment(state, { payload}) {
            const newComment = {
                id: Date.now(),
                timestamp: new Date().toISOString(),
                ...payload
            }
            state.comments.unshift(newComment);
            console.log(state);

            localStorage.setItem('comments', JSON.stringify(state.comments))
        },

        // 删除评论
        removeComment(state, {payload}) {
            state.comments = state.comments.filter((item:any) => {
                return item.id !== payload
            })
            localStorage.setItem('comments', JSON.stringify(state.comments))
        },

        // 编辑评论
        updateComment(state, {payload}) {
            const comment = state.comments.find((item:any) => {
                return item.id  === payload.id
            })
            if (comment) {
                comment.content = payload.content
            }
            localStorage.setItem('comments', JSON.stringify(state.comments))
        }

    }
})

export const {addComment,removeComment ,updateComment } = commentsSlice.actions
export default commentsSlice.reducer
